import { defineStore } from 'pinia'
import type { Task, AppSettings } from '@/types'

// 从本地存储加载设置
const loadSettings = (): AppSettings => {
  try {
    const saved = localStorage.getItem('app_settings')
    if (saved) {
      return JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
  return {
    openAIKey: '',
    aiEnabled: true,
    voiceEnabled: true,
    autoPlay: true
  }
}

interface State {
  settings: AppSettings
  tasks: Task[]
  currentTask: Task | null
}

export const useAppStore = defineStore('app', {
  state: (): State => ({
    settings: loadSettings(),
    tasks: [],
    currentTask: null
  }),
  
  actions: {
    updateSettings(settings: Partial<AppSettings>) {
      this.settings = { ...this.settings, ...settings }
      // 保存到本地存储
      localStorage.setItem('app_settings', JSON.stringify(this.settings))
    },
    
    addTask(task: Task) {
      this.tasks.push(task)
    },
    
    updateTask(taskId: string, updates: Partial<Task>) {
      const index = this.tasks.findIndex(t => t.id === taskId)
      if (index !== -1) {
        this.tasks[index] = { ...this.tasks[index], ...updates }
      }
    }
  }
}) 